package com.angenela.imageshare.activity;


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.angenela.imageshare.R;
import com.angenela.imageshare.dto.TagDTO;
import com.angenela.imageshare.ui.home.HomeFragment;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.tencent.connect.share.QQShare;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import java.io.IOException;
import java.lang.reflect.Type;

import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


public class ImageActivity extends AppCompatActivity {

    private static final String STAR_URL = "http://122.9.152.182:8080/star/";
    ImageView iv_detail_image;
    ImageView iv_detail_avatar;
    ImageView iv_detail_start;
    ImageView iv_detail_share;
    TextView tv_detail_username;
    TextView tv_detail_start;
    Tencent mTencent;
    int flag;
    int imageID;
    int userId;
    int startCount;

    MyIUiListener listener;

    Intent intent1 = null;


    String src;

    public static void sharedToWx(Context context, Uri uri) {
        //        if(sendMsg == null) return;
        Intent intent = new Intent(Intent.ACTION_SEND);
        if (!(context instanceof Activity)) {
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        //intent.setType("text/plain"); //文本分享
        intent.setType("image/*");
        if (uri != null) {
            intent.putExtra(Intent.EXTRA_STREAM, uri);
        }
        intent.setPackage("com.tencent.mobileqq");
        intent.setClassName("com.tencent.mobileqq", "com.tencent.mobileqq.activity.JumpActivity");//QQ
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_image);


    // Tencent类是SDK的主要实现类，开发者可通过Tencent类访问腾讯开放的OpenAPI。
    // 其中APP_ID是分配给第三方应用的appid，类型为String。
    // 其中Authorities为 Manifest文件中注册FileProvider时设置的authorities属性值
        mTencent = Tencent.createInstance("101974948", this.getApplicationContext());
    // 1.4版本:此处需新增参数，传入应用程序的全局context，可通过activity的getApplicationContext方法获取
    // 初始化视图
    //        initViews();


        iv_detail_image = findViewById(R.id.iv_detail_image);
        iv_detail_avatar = findViewById(R.id.iv_detail_avatar);
        iv_detail_start = findViewById(R.id.iv_detail_star);
        iv_detail_share = findViewById(R.id.iv_detail_share);
        listener = new MyIUiListener();

        tv_detail_start = findViewById(R.id.tv_detail_star);
        tv_detail_username = findViewById(R.id.tv_detail_username);


        Intent intent = getIntent();
        src = intent.getStringExtra(HomeFragment.ImageSrc);
        String avatar = intent.getStringExtra(HomeFragment.ImageAvatar);
        startCount = intent.getIntExtra(HomeFragment.ImageStar, 0);
        String username = intent.getStringExtra(HomeFragment.ImageUsername);
        flag = intent.getIntExtra(HomeFragment.ImageFlag, 0);
        imageID = intent.getIntExtra(HomeFragment.ImageId, -1);
        userId = intent.getIntExtra(HomeFragment.ImageUserId, -1);

        Glide.with(this).load(src).into(iv_detail_image);
        Glide.with(this).load(avatar).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(iv_detail_avatar);
        if (flag == 1) {
            Glide.with(this).load(R.drawable.shoucang).into(iv_detail_start);
        } else {
            Glide.with(this).load(R.drawable.shoucang_01).into(iv_detail_start);
        }

        Glide.with(this).load(R.drawable.share).into(iv_detail_share);

        tv_detail_start.setText(String.valueOf(startCount));
        tv_detail_username.setText(username);

        iv_detail_start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent intent1 = new Intent();
                setResult(0);

                if (flag == 1) {
                    flag = 0;

                    startCount = startCount - 1;
                    intent1.putExtra("delete",imageID);
                    intent1.putExtra("startCount",startCount);
                    setResult(1, intent1);
                    tv_detail_start.setText(String.valueOf(startCount));
                    try {
                        deleteStar(String.valueOf(imageID), String.valueOf(userId));
                        Glide.with(ImageActivity.this).load(R.drawable.shoucang_01).into(iv_detail_start);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                } else if (flag == 0) {
                    flag = 1;

                    startCount = startCount + 1;

                    intent1.putExtra("add",imageID);
                    intent1.putExtra("startCount",startCount);
                    setResult(2, intent1);
                    tv_detail_start.setText(String.valueOf(startCount));
                    try {
                        addStar(String.valueOf(imageID), String.valueOf(userId));
                        Glide.with(ImageActivity.this).load(R.drawable.shoucang).into(iv_detail_start);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        });


        iv_detail_share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onClickShare();
                System.out.println("分享");

            }
        });
    }



    public void addStar(String imageId, String userId) throws IOException {
        OkHttpClient okHttpClient = new OkHttpClient();

        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("imageId ", imageId)
                .addFormDataPart("userId", userId)
                .build();

        Request request = new Request.Builder()
                .url(STAR_URL + "add")
                .post(requestBody)
                .build();


        Response response = okHttpClient.newCall(request).execute();

        Gson gson = new Gson();
        Type jsonType = new TypeToken<TagDTO>() {
        }.getType();
        TagDTO result = gson.fromJson(response.body().string(), jsonType);


    }

    public void deleteStar(String imageId, String userId) throws IOException {
        OkHttpClient okHttpClient = new OkHttpClient();

        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("imageId ", imageId)
                .addFormDataPart("userId", userId)
                .build();

        Request request = new Request.Builder()
                .url(STAR_URL + "delete")
                .post(requestBody)
                .build();

        Response response = okHttpClient.newCall(request).execute();

        Gson gson = new Gson();
        Type jsonType = new TypeToken<TagDTO>() {
        }.getType();
        TagDTO result = gson.fromJson(response.body().string(), jsonType);


    }


private void onClickShare() {
    Bundle params = new Bundle();
    params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
    params.putString(QQShare.SHARE_TO_QQ_TITLE, "标题");// 标题
    params.putString(QQShare.SHARE_TO_QQ_SUMMARY, "要分享的摘要");// 摘要
    params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, "http://www.baidu.com");// 内容地址
    params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, src);// 网络图片地址　　params.putString(QQShare.SHARE_TO_QQ_APP_NAME, "应用名称");// 应用名称
    params.putString(QQShare.SHARE_TO_QQ_EXT_INT, "其它附加功能");
    // 分享操作要在主线程中完成
    mTencent.shareToQQ(ImageActivity.this, params, listener);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (null != mTencent) {
        Tencent.onActivityResultData(requestCode, resultCode, data, listener);
    }
}

class MyIUiListener implements IUiListener {

    @Override
    public void onComplete(Object o) {
        Toast.makeText(ImageActivity.this, "分享成功！", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onError(UiError uiError) {
        Toast.makeText(ImageActivity.this, uiError.errorMessage, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onCancel() {
        Toast.makeText(ImageActivity.this, "分享取消！", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onWarning(int i) {
    }
}


}